package com.ticket.sass.admin.annotation;

import com.ticket.sass.admin.dto.input.coupons.CouponAddInput;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;
import java.time.LocalDate;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ActivateTimeRange.ActivateTimeRangeValidator.class)
@Documented
public @interface ActivateTimeRange {
    String message() default "生效类型与日期范围不匹配";
    
    Class<?>[] groups() default {};
    
    Class<? extends Payload>[] payload() default {};
    
    class ActivateTimeRangeValidator implements ConstraintValidator<ActivateTimeRange, Object> {
        @Override
        public boolean isValid(Object value, ConstraintValidatorContext context) {
            if (value instanceof CouponAddInput) {
                CouponAddInput input = (CouponAddInput) value;
                return check(input.getActivateType(), input.getStartDate(), input.getEndDate(), input.getActivateStart(), input.getActivateEnd());
            }
            
//            if (value instanceof CouponUpdInput) {
//                CouponUpdInput input = (CouponUpdInput) value;
//                return check(input.getActivateType(), input.getStartDate(), input.getEndDate(), input.getActivateStart(), input.getActivateEnd());
//            }
            return false;
        }
        
        private boolean check(Short activateType, LocalDate startDate, LocalDate endDate, Integer activateStart, Integer activateEnd) {
            if (activateType == null) {
                return false;
            }
            // 生效类型：1 指定日期范围，2 领取后指定
            boolean isDateRangeActivation = (activateType == 1);
            boolean isAfterReceiveActivation = (activateType == 2);
            
            if (isDateRangeActivation) {
                return startDate != null && endDate != null && activateStart == null && activateEnd == null;
            } else if (isAfterReceiveActivation) {
                return startDate == null && endDate == null && activateStart != null && activateEnd != null;
            }

            return false;
        }
    }
}

